package main

import (
	"context"
	"fmt"
	"github.com/goccy/go-json"
	"order_bff/order_proto"
	"order_bff/pkg"
	"os"
	"time"

	"github.com/apache/rocketmq-client-go/v2"
	"github.com/apache/rocketmq-client-go/v2/consumer"
	"github.com/apache/rocketmq-client-go/v2/primitive"
)

func main() {
	c, _ := rocketmq.NewPushConsumer(
		consumer.WithGroupName("testGroup"),
		consumer.WithNsResolver(primitive.NewPassthroughResolver([]string{"10.3.189.13:9876"})),
	)
	err := c.Subscribe("test", consumer.MessageSelector{}, func(ctx context.Context,
		msgs ...*primitive.MessageExt) (consumer.ConsumeResult, error) {
		for i := range msgs {
			type Order struct {
				UserIdInt  int
				GoodsIdInt int
				StockInt   int
			}
			var order Order
			json.Unmarshal(msgs[i].Body, &order)
			comment := pkg.Comment()
			_, err := comment.CreateOrder(context.Background(), &order_proto.CreateOrderRequest{
				UserId:  int32(order.UserIdInt),
				GoodsId: int32(order.GoodsIdInt),
				Stock:   int32(order.StockInt),
			})
			if err != nil {
				return consumer.Rollback, nil
			}
		}

		return consumer.ConsumeSuccess, nil
	})
	if err != nil {
		fmt.Println(err.Error())
	}
	// Note: start after subscribe
	err = c.Start()
	if err != nil {
		fmt.Println(err.Error())
		os.Exit(-1)
	}
	time.Sleep(time.Hour)
	err = c.Shutdown()
	if err != nil {
		fmt.Printf("shutdown Consumer error: %s", err.Error())
	}
}
